<template>
    <div class="boxs">
        <local v-show="locabob" />
        <div class="topNav">
            <div>
                <h4>公司聊天室</h4>
            </div>
            <div class="topNav_right">
                <div><el-button type="success" @click="fileOut" style="margin-right: 10px;">导出聊天记录</el-button></div>
                <label for="imgChan">
                    <p class="files">
                        更改背景图
                    </p>
                </label>
                <input type="file" style="display: none;" @change="imgBeiChan" id="imgChan">
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="#626AEF" title="确定删除吗?"
                    @confirm="confirmEvent">
                    <template #reference>
                        <el-button type="primary" v-show="store.role == 0">
                            删除全部记录
                        </el-button>
                    </template>
                </el-popconfirm>
            </div>
        </div>
        <div class="content" ref="contents"
            :style="{ backgroundImage: `url(${imgss})`, backgroundRepeat: 'no-repeat', backgroundSize: '100%', backgroundPosition: 'center,center' }">
            <ul>
                <li v-for="(    item, index    ) in     chats    " :key="item"
                    :class="item.nickname == userItem.nickname ? 'content_right' : 'content_left'">
                    <div class="imgs" v-show="item.nickname != userItem.nickname" @click="nameChan(item.nickname)">
                        <img :src="item.url" alt="">
                    </div>
                    <div class="contents">
                        <p>{{ item.nickname }}</p>
                        <p @click.right.prevent="confirmEvent1(item.id)">{{ item.texts }}</p>
                    </div>
                    <div class="imgs" v-show="item.nickname == userItem.nickname">
                        <img :src="item.url" alt="">
                    </div>
                </li>
            </ul>
        </div>
        <div class="chats" @keyup.enter="goChat">
            <div class="chats_input">
                <textarea v-model="input"></textarea>
            </div>
            <div>
                <el-button type="success" size="small" class="chats_but" @click="goChat">
                    发送
                </el-button>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, computed, watch, onMounted, getCurrentInstance, nextTick } from 'vue'
import { useIndexStore } from '../../pinia';
import { ElMessage } from "element-plus"
import { request } from '@/utils/axios/request.js'
import local from '@/components/local.vue'
import { initWebSocket, sendSock } from '../../utils/websocket_chat'

// 聊天背景
let imgss = ref('/images/pexels-maxime-francis-2246476.jpg')
let imgUrls = localStorage.getItem('imgBeiChan')
if (imgUrls) {
    imgss.value = imgUrls
}
// 更换背景
let imgBeiChan = async (event) => {
    if (event.target.files.length == 0) {
        ElMessage.warning('您未上传图片')
        return
    }
    let file = event.target.files[0]
    if (!/\.(jpg|png|JPG|PNG|gif|webp|jpeg)$/.test(file.name)) {
        ElMessage.warning('图片格式错误')
        return
    }
    if (file.size >= 8192000) {
        ElMessage.warning('图片大小必须小于8M')
        return
    }
    const formData = new FormData();
    formData.append('avatar', file);
    try {
        let imgUrl = await request({
            url: '/admin/imgUrl',
            method: 'post',
            data: formData,
            headers: { 'content-type': 'multipart/form-data' }
        })
        imgss.value = imgUrl.url
        localStorage.setItem('imgBeiChan', imgUrl.url)
    } catch (err) {
        console.log(err);
    }
}



//str:所传入需要过滤的字符串 
function filterSensitiveWords(str) {
    const sensitiveWords = ["CNM", "SB", "NMSL", "MB", "FUCK", 'cnm', 'sb', 'nmsl', 'mb', 'fuck', '装逼', '草泥马', '特么的'
        , '色逼'
        , '撕逼'
        , '玛拉个逼'
        , '爆菊'
        , 'JB'
        , '呆逼'
        , '屌'
        , '齐B短裙'
        , '法克鱿'
        , '丢你老母'
        , '打飞机'
        , '傻逼'
        , '绿茶婊'
        , '你妈的'
        , '婊渣'
        , '屌爆了'
        , '买了个表'
        , '已撸'
        , '妈蛋'
        , '逗逼'
        , '我靠'
        , '碧莲'
        , '碧池'
        , '日了狗'
        , '吃翔'
        , '你妹'
        , '杂种'
        , '黑鬼'
        , '东亚病夫'
        , '蛮夷'
        , '性交'
        , '生殖器'
        , '艹你'
        , '我草泥马'
        , '你妈死了'
        , '你生儿子没屁眼'
        , '你他妈'
        , '我日你大爸'
        , '我日你个仙人板板'
        , '你他妈真是个小可爱'
        , '好想摸你'
        , '老板大傻逼'
        , '老板草泥马'
        , '我草你妈'
        , '你全家死光光'
        , '套你猴子'
        , '小瘪三'
        , '他妈了个巴子'
        , '抓到你就嘿嘿嘿'
        , '涩情'
        , '黄色电影'
        , '祝你全家出车祸'
    ]; // 敏感词列表
    const regExp = new RegExp(sensitiveWords.join('|'), 'gi'); // 构造正则表达式
    return str.replace(regExp, '*'.repeat(str.length)); // 将敏感词替换为 ***
}



let that = getCurrentInstance()
let locabob = ref(false)
const store = useIndexStore()
// 聊天输入框
let input = ref('')

// @某人功能
const nameChan = (nickname) => {
    input.value = input.value.concat(`@${nickname} `)
}


// 获取当前登录账号
let usernameLoca = localStorage.getItem('username')
let userItem = ref({})
let findAll = null
if (usernameLoca) {
    findAll = async () => {
        try {
            locabob.value = true
            let newdata = await request({
                url: `/admin/user/users1?username=${usernameLoca}`,
                method: 'get'
            })
            newdata.data.forEach(item => {
                item.role = item.role == 0 ? '超级管理员' : item.role == 1 ? '普通管理员' : '普通员工'
                item.status = item.status == 1 ? '正常' : '停用'
            })
            userItem.value = newdata.data[0]
        } catch (err) {
            console.log(err);
        }
        locabob.value = false
    }
    findAll()
}

// 聊天记录
let chats = ref([])
// 获取聊天记录
let findAlls = null

// 文件导出
import * as XLSX from 'xlsx'
const fileOut = () => {
    if (confirm('确认导出吗')) {
        const data = chats.value; // json数据
        const sheetName = 'chat'; // 表格名称
        const sheetHeader = ["nickname", "url", "texts", "create_at"]; // 表头
        const sheetData = data.map(item => [item.nickname, item.url, item.texts, item.create_at]); // 表格数据
        sheetData.unshift(sheetHeader); // 将表头插入表格数据第一行
        const worksheet = XLSX.utils.aoa_to_sheet(sheetData); // 将表格数据转换为worksheet
        const workbook = XLSX.utils.book_new(); // 创建workbook
        XLSX.utils.book_append_sheet(workbook, worksheet, sheetName); // 将worksheet插入workbook
        XLSX.writeFile(workbook, 'chat.xlsx'); // 下载表格
    }
}


// 聊天发送
let obj = ref({})
let goChat = null
onMounted(() => {
    let tents = that.refs.contents
    findAlls = async () => {
        try {
            // locabob.value = true
            let resData = await request({
                url: '/admin/chat/cahtAll',
                method: 'get',
            })
            chats.value = resData.data.sort((a, b) => a.id - b.id).slice(resData.data.length - 60 < 0 ? 0 : resData.data.length - 60, resData.data.length)
        } catch (err) {
            console.log(err);
        }
        // locabob.value = false
        nextTick(() => {
            tents.scrollTop = tents.scrollHeight
        })
    }
    // 实时聊天
    initWebSocket()
    sendSock({}, data => {
        let bob = false
        let newData = data.sort((a, b) => a.id - b.id).slice(data.length - 60 < 0 ? 0 : data.length - 60, data.length)
        newData.forEach(item => {
            bob = chats.value.some(items => items.texts == item.texts)
        })
        chats.value = newData
        if (!bob) {
            nextTick(() => {
                tents.scrollTop = tents.scrollHeight
            })
        }
    })
    findAlls()
    goChat = async () => {
        input.value = input.value.replace(/\n*/gm, '')
        input.value = filterSensitiveWords(input.value)
        if (input.value == '') {
            return
        }
        obj.value.nickname = userItem.value.nickname
        obj.value.url = userItem.value.url
        obj.value.texts = input.value
        obj.value.create_at = new Date().toLocaleString()
        try {
            // locabob.value = true
            let data = await request({
                url: '/admin/chat/chats',
                method: 'post',
                data: obj.value
            })
            findAlls()
            input.value = ''
        } catch (err) {
            console.log(err);
        }
        // locabob.value = false
    }
})

// // 单条信息删除
let confirmEvent1 = async (id) => {
    let nick = chats.value.find((item) => item.id == id).nickname
    if (nick != userItem.value.nickname && store.role == 2) {
        ElMessage.warning("您没有权限删除其他人的信息")
        return
    }
    if (confirm("确认删除吗？")) {
        try {
            // locabob.value = true
            let data = await request({
                url: '/admin/chat/chats',
                method: 'delete',
                data: { id }
            })
            findAlls()
            ElMessage.success(data.message)
        } catch (err) {
            console.log(err);
        }
        // locabob.value = false
    }
}

// 全部删除确定事件
let confirmEvent = async () => {
    try {
        locabob.value = true
        let data = await request({
            url: '/admin/chat/chats1',
            method: 'delete',
        })
        findAlls()
        ElMessage.success(data.message)
    } catch (err) {
        console.log(err);
    }
    locabob.value = false
}

</script>
<style scoped lang="less">
.files {
    display: inline-block;
    padding: 0 10px;
    height: 32px;
    line-height: 32px;
    background-color: rgba(1, 137, 1, 0.6);
    border-radius: 5px;
    color: white;
    font-size: 14px;
    margin-right: 10px;
    box-sizing: border-box;
    transform: translateY(2px);
    transition: all 0.2s linear;

    &:hover {
        background-color: rgba(1, 137, 1);
    }
}

.boxs {
    display: flex;
    flex-direction: column;
    height: calc(100% - 85px);
    justify-content: space-between;

    .topNav {
        display: flex;
        height: 50px;
        // background-color: white;
        justify-content: space-between;
        align-items: center;
        padding: 0 30px;
        border-bottom: 0.5px solid #e8e8e8;
        box-shadow: 0 1px 5px #e8e8e8;

        .topNav_right {
            display: flex;
            align-items: center;
        }
    }

    .chats {
        display: flex;
        height: 110px;
        // background-color: white;
        justify-content: space-between;
        align-items: center;
        padding: 0 30px 0 0;
        border-top: 0.5px solid #e8e8e8;
        box-shadow: 0 -1px 5px #e8e8e8;

        .chats_but {
            height: 30px;
            width: 60px;
            font-size: 16px;
        }

        .chats_input {
            width: calc(100% - 100px);
            height: 100%;

            textarea {
                box-sizing: border-box;
                width: 100%;
                height: 100%;
                padding: 10px;
                font-size: 16px;
                outline: none;
                border: 1px solid transparent;
                font-weight: 560;
            }
        }
    }

    .content {
        height: calc(100% - 152px);
        // padding: 0 30px;

        ul {
            display: flex;
            min-height: 100%;
            flex-direction: column;
            justify-content: end;
            scroll-behavior: smooth;
            user-select: none;
            position: relative;
            padding: 0 30px;

            &::after {
                content: '';
                width: 100%;
                height: 100%;
                position: absolute;
                top: 0;
                left: 0;
                z-index: 1;
                background-color: rgba(0, 0, 0, 0.3);
            }

            li {
                position: relative;
                z-index: 2;
                flex-shrink: 0;
            }
        }
    }
}


.content_left {
    display: flex;
    margin: 20px 0;
    align-self: flex-start;

    .imgs {
        height: 50px;
        width: 50px;
        flex-shrink: 0;

        img {
            height: 100%;
            width: 100%;
            border-radius: 5px;
        }
    }

    .contents {
        display: flex;
        flex-direction: column;
        height: 100%;
        margin-left: 15px;

        p {
            // width: 70%;
            word-wrap: break-word;
        }

        p:nth-child(1) {
            font-size: 14px;
            color: #dddddd;
        }

        p:nth-child(2) {
            background-color: white;
            padding: 5px;
            padding: 5px 10px;
            border-radius: 5px;
        }
    }
}

.content_right {
    display: flex;
    margin: 20px 0;
    align-self: flex-end;

    .imgs {
        height: 50px;
        width: 50px;
        flex-shrink: 0;

        img {
            height: 100%;
            width: 100%;
            border-radius: 5px;
        }
    }

    .contents {
        display: flex;
        flex-direction: column;
        height: 100%;
        margin-right: 15px;

        p {
            // width: 70%;
            word-wrap: break-word;
            text-align: right;
            align-self: flex-end;
        }

        p:nth-child(1) {
            font-size: 14px;
            color: #dddddd;
        }

        p:nth-child(2) {
            background-color: rgb(6, 248, 22);
            padding: 5px 10px;
            border-radius: 5px;
        }
    }
}
</style>